<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018-06-07
 * Time: 13:38
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\Active as ActiveModel;
use app\api\model\ShareRecord;
use app\api\service\Token as TokenService;
use app\api\validate\CheckActive;
use app\lib\exception\ActiveException;
use app\lib\exception\MissException;
use think\Db;
use think\Exception;
use app\api\model\User as UserModel;


class Active extends BaseController
{
    // 获取所有活动信息
    public function getActiveList(){
        $now_time = date("Y-m-d H:i:s");
        $activeAll = ActiveModel::where('status', '=', 1)->whereNull('delete_time')->where('startTime','<',$now_time)->where('endTime','>',$now_time)->select();
        if($activeAll->isEmpty()){
            throw new ActiveException([
                'msg' => '暂无抽奖活动，或未到开启时间，请等待',
                'errorCode' => 40011
            ]);
        }
        return $activeAll;
    }

    // 获取某个活动详情信息
    public function getActiveByID($id){
        $validate = new CheckActive();
        $validate->goCheck();
        $uid = TokenService::getCurrentUid();
        $shareInfo = input('post.');
        if(!empty($shareInfo)){
            if($shareInfo['shareUid'] && $uid != $shareInfo['shareUid']){
                $share_uid = $shareInfo['shareUid'];
                Db::startTrans();
                try{
                    $shareRecord = ShareRecord::where('share_uid', '=', $shareInfo['shareUid'])->where('uid', '=', $uid)->find();
                    if(empty($shareRecord)){
                        $share = new ShareRecord();
                        $share->share_uid = $shareInfo['shareUid'];
                        $share->uid = $uid;
                        $share->save();
                        $user = UserModel::get($share_uid);
                        $user->lottery_count = $user->lottery_count + 1;
                        $user->save();
                    }
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                }
            }
            $active = ActiveModel::getActiveById($id);
        }else{
            $active = ActiveModel::getActiveById($id);
        }
        if (!$active) {
            throw new MissException([
                'msg' => '该抽奖活动，未到开启时间或已结束，请等待',
                'errorCode' => 40000
            ]);
        }
        return $active;
    }
}